<template>
  <div>
    <el-form :model="form" ref="form" name="basic" label-width="80px" autocomplete="off" style="margin-top: 10px;margin-left: 10px;">
      <el-row>
        <el-col :span="6">
          <CompanySelect :compName.sync="form.companyName" />
        </el-col>
      </el-row>
    </el-form>
    <div style="margin-right: 15px;">
      <el-upload class="upload-demo" style="float: right;margin-bottom: 5px;" action=""
        :http-request="handleUpload1" :show-file-list="false">
        <el-button type="warning" size="mini">导入</el-button>
        <div slot="tip" class="el-upload__tip"></div>
      </el-upload>
      <el-button type="primary" style="float: right;margin-right: 10px;" size="mini"
        @click="clickDlTemp">导出</el-button>
      <el-button type="primary" style="float: right;margin-right: 10px;" size="mini"
        @click="clickAdd">新增</el-button>
      <el-button type="success" style="float: right;margin-bottom: 5px;margin-right: 10px;"
        size="mini" @click="clickQuery">查询</el-button>
    </div>
    <div style="padding: 10px 20px;">
      <el-table :data="tableData" :key="key" style="width: 100%;border: solid 1px #c0c0c0;"
        row-key="index" header-row-class-name="table_header"
        :header-cell-style="{ borderColor: '#C0C0C0' }" :cell-style="{ borderColor: '#C0C0C0' }"
        border @cell-dblclick="doubleClick" id="out-table">
        <!-- <el-table-column v-for="column,index in columns" :key="index" :prop="column.dataIndex"
          :label="column.title" :align="column.align" :width="column.width?column.width:'auto' ">
        </el-table-column> -->
        <el-table-column prop="companyName" label="企业名称" align="left" min-width="250px">
        </el-table-column>
        <el-table-column prop="companyShort" label="企业简称" align="center" min-width="100px">
        </el-table-column>
        <el-table-column prop="credCode" label="营业执照代码" align="center" min-width="200px">
          <template slot-scope="scope">
            <el-input v-focus v-if="scope.row[scope.column.property + 'Show']" clearable
              v-model="scope.row.credCode"
              @keyup.enter.native="blurInput"></el-input>
            <!-- @blur="onBlur(scope.row, scope.column)" -->
            <span v-else>{{ scope.row.credCode }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="userName" label="企业账号" align="center" min-width="250px">
        </el-table-column>
        <el-table-column prop="password" label="账号密码" align="center" min-width="100px">
        </el-table-column>

        <el-table-column prop="headName" label="主要负责人" align="center" min-width="110px">
          <template slot-scope="scope">
            <el-input v-focus v-if="scope.row[scope.column.property + 'Show']" clearable
              v-model="scope.row.headName" @keyup.enter.native="blurInput"
              @blur="onBlur(scope.row, scope.column)"></el-input>
            <span v-else>{{ scope.row.headName }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="headPhone" label="主要负责人电话" align="center" min-width="120px">
          <template slot-scope="scope">
            <el-input v-focus v-if="scope.row[scope.column.property + 'Show']" clearable
              v-model="scope.row.headPhone" @keyup.enter.native="blurInput"
              @blur="onBlur(scope.row, scope.column)"></el-input>
            <span v-else>{{ scope.row.headPhone }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="adminName" label="安全管理员" align="center" min-width="110px">
          <template slot-scope="scope">
            <el-input v-focus v-if="scope.row[scope.column.property + 'Show']" clearable
              v-model="scope.row.adminName" @keyup.enter.native="blurInput"
              @blur="onBlur(scope.row, scope.column)"></el-input>
            <span v-else>{{ scope.row.adminName }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="adminPhone" label="安全管理员电话" align="center" min-width="120px">
          <template slot-scope="scope">
            <el-input v-focus v-if="scope.row[scope.column.property + 'Show']" clearable
              v-model="scope.row.adminPhone" @keyup.enter.native="blurInput"
              @blur="onBlur(scope.row, scope.column)"></el-input>
            <span v-else>{{ scope.row.adminPhone }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="zoneNo" label="区块" align="center" min-width="90px">
          <template slot-scope="scope">
            <el-input v-focus v-if="scope.row[scope.column.property + 'Show']" clearable
              v-model="scope.row.zoneNo" @keyup.enter.native="blurInput"
              @blur="onBlur(scope.row, scope.column)"></el-input>
            <span v-else>{{ scope.row.zoneNo }}</span>
          </template>
        </el-table-column>

        <el-table-column prop="isHouseOwner" label="资产方" align="center" min-width="80px">
          <template slot-scope="scope">
            <el-input v-focus v-if="scope.row[scope.column.property + 'Show']" clearable
              v-model="scope.row.isHouseOwner" @keyup.enter.native="blurInput"
              @blur="onBlur(scope.row, scope.column)"></el-input>
            <span v-else>{{ scope.row.isHouseOwner  }}</span>
          </template>
        </el-table-column>

        <el-table-column label="操作" align="center">
          <template slot-scope="scope">
            <i @click="clickDel(scope.$index, scope.row)" class="el-icon-delete"
              style="margin-right: 10px;cursor: pointer;"></i>

            <i @click="clickInfo(scope.$index, scope.row)" class="el-icon-info"
              style="cursor: pointer;"></i>

            <!-- <el-button size="mini" >编辑</el-button> -->
            <!-- <el-button size="mini" type="danger"
            >删除</el-button> -->

          </template>
        </el-table-column>
      </el-table>

    </div>
    <el-pagination background layout="prev, pager, next" :total="total_size" :page-size="100"
      :current-page="page_no">
    </el-pagination>

    <UpdateModal ref="UpdateModalRef" :clickQuery="clickQuery" :saveFun="updateCompany"
      :addFun="addCompany" />

    <el-dialog title="删除提示" :visible.sync="delVisible" width="30%">
      <span>确定删除吗？</span>
      <span slot="footer" class="dialog-footer">
        <el-button @click="delVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleDelete">确 定</el-button>
      </span>
    </el-dialog>

    <!-- <Detail ref="DetailRef" /> -->
  </div>

</template>
<script>
import UpdateModal from './updateModal';
// import Detail from './updateModal/detail.vue';

import {
  queryCompanyList,
  updateCompany,
  addCompany,
  delCompany,
  importExcel,
} from '@/service/company/index';
import FileSaver from 'file-saver';
import * as XLSX from 'xlsx';
import columns from './table';
// import { tableMixin } from '@/mixin/table';
import CompanySelect from '@/components/CompanySelect';

export default {
  components: { UpdateModal,CompanySelect },
  // mixins: [tableMixin],

  data() {
    return {
      data: [],
      key: Math.random(),
      pagination: {
        showLessItems: true,
        showQuickJumper: true,
        showSizeChanger: true,
      },
      query: {},
      columns: columns,
      currItem: {},
      page_no: 0,
      page_size: 100,
      form: {},
      tableLoading: false,
      tableData: [],
      total_size: 0,
      loading: false,
      updateCompany,
      addCompany,
      queryCompanyList,
      delVisible: false,
    };
  },

  methods: {
    clickShowEdit(index, record) {
      this.$refs.UpdateModalRef.openEditDialog({ ...record });
    },
    clickAdd(record) {
      this.$refs.UpdateModalRef.openAddDialog();
    },
    clickDel(index, row) {
      this.delVisible = true;
      this.currItem = { ...row };
    },
    clickInfo(index, row) {
      this.$router.push({
        name: 'companyInfo',
        params: { companyName: row.companyName },
      });
    },
    clickDlTemp(index, row) {
      console.log('XLSX', XLSX, document.querySelector('#out-table'));
      var wb = XLSX.utils.table_to_book(document.querySelector('#out-table'));
      var wbout = XLSX.write(wb, {
        bookType: 'xlsx',
        bookSST: true,
        type: 'array',
      });
      try {
        const date = new Date();
        let dateStr =
          date.getFullYear() +
          '-' +
          (date.getMonth() + 1) +
          '-' +
          date.getDate();
        FileSaver.saveAs(
          new Blob([wbout], {
            type: 'application/octet-stream',
          }),
          '企业档案-' + dateStr + '.xlsx'
        );
      } catch (e) {
        if (typeof console !== 'undefined') console.log(e, wbout);
      }
      return wbout;
    },
    blurInput(e){
      e.target.blur()
    },
    doubleClick(row, column) {
      // 避免点击过快导致多个输入框处于焦点状态
      row[column.property + 'Show'] = false;
      // 避免点击其他单元格导致表格刷新

      console.log('column.property', column.property);
      if (
        ![
          'credCode',
          'headName',
          'headPhone',
          'adminName',
          'adminPhone',
          'zoneNo',
          'isHouseOwner',
        ].includes(column.property)
      )
        return;
      row[column.property + 'Show'] = true;
      this.key = Math.random();
      console.log('row', row);
      // this.updateTable(row);
    },
    //输入框失焦事件
    onBlur(row, column) {
      console.log('column', column);
      row[column.property + 'Show'] = false;
      this.updateTable(row);
    },
    async saveData(row) {
      const res = await updateCompany(row);
      if (res.success) {
        this.$message.success('保存成功');
      } else {
        this.$message.error('保存失败');
      }
      this.clickQuery();
    },

    //更新表格
    updateTable(row) {
      this.saveData(row);
    },

    getFD(fileObj) {
      const formData = new FormData();
      formData.append('file', fileObj.file);
      return formData;
    },
    async handleUpload1(fileObj) {
      const fd = this.getFD(fileObj);
      let res = await importExcel(fd);
      if (res.success) {
        this.clickQuery();
      }
      return false;
    },

    async handleDelete() {
      this.delVisible = false;
      const res = await delCompany({
        ...this.currItem,
      });
      if (res.success) {
        this.clickQuery();
      } else {
      }
    },

    async clickQuery() {
      this.loading = true;
      const data = await queryCompanyList({
        ...this.form,
        page_no: this.page_no,
        page_size: this.page_size,
      });
      if (data.success) {
        this.total_size = data.total;
        this.tableData = data.dataList;
      } else {
        this.total_size = 0;
        this.tableData = [];
      }
      this.loading = false;
    },

    // updateCompany(){

    // }
  },
  created() {
    const date = new Date();
    const currMonth = date.getFullYear() + '-' + (date.getMonth() + 1);
    this.$set(this.form, 'scoreMonth', currMonth);
    // this.form.scoreMonth = currMonth;
    console.log('this.form.currMonth', this.form.currMonth);
  },

  mounted() {
    console.log('ff:' + this.tableData);
    console.log('ff11:' + this.clickQuery);

    this.clickQuery(queryCompanyList);
  },
};
</script>
<style scoped>
/deep/ .table_header th {
  background-color: #e3e3e3 !important;
  height: 40px;
}

::v-deep .el-table .el-table__cell {
  padding: 4px 0px;
}
</style>